<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

/**
 * 前台公共库文件
 * 主要定义前台公共函数库
 */

/**
 * 检测验证码
 * @param  integer $id 验证码ID
 * @return boolean     检测结果
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function check_verify($code, $id = 1){
	$verify = new \Think\Verify();
	return $verify->check($code, $id);
}
/**
 * 判断是否为微信访问
 * @return boolean
 */
function is_wechat()
{
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return true;
    }
    return false;
}
/**
 *资源文件 url
 */
function get_url($cover_id){
    $path = get_cover($cover_id,'url');
    $path_info = parse_url($path);
    if (!empty($path_info['scheme'])) {
        return $path;
    }else{
        return $path ? mb_substr($_SERVER["HTTP_REFERER"], 0, strrpos($_SERVER["HTTP_REFERER"], "/")).$path : '';
    }
}

/**
 * 获取列表总行数
 * @param  string  $category 分类ID
 * @param  integer $status   数据状态
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function get_list_count($category, $status = 1){
    static $count;
    if(!isset($count[$category])){
        $count[$category] = D('Document')->listCount($category, $status);
    }
    return $count[$category];
}

/**
 * 获取段落总数
 * @param  string $id 文档ID
 * @return integer    段落总数
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function get_part_count($id){
    static $count;
    if(!isset($count[$id])){
        $count[$id] = D('Document')->partCount($id);
    }
    return $count[$id];
}

/**
 * 获取导航URL
 * @param  string $url 导航URL
 * @return string      解析或的url
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function get_nav_url($url){
    switch ($url) {
        case 'http://' === substr($url, 0, 7):
        case '#' === substr($url, 0, 1):
            break;        
        default:
            $url = U($url);
            break;
    }
    return $url;
}

function valid_login($save_cookie=1){
   if(!is_login()){
       if($save_cookie){
        Cookie('__orpage__', __SELF__);
       }
       redirect(U('User/login'));
   }
}
function int_to_string(&$data,$map=array('status'=>array(1=>'正常',-1=>'删除',0=>'禁用',2=>'未审核',3=>'草稿'))) {
    if($data === false || $data === null ){
        return $data;
    }
    $data = (array)$data;
    foreach ($data as $key => $row){
        foreach ($map as $col=>$pair){
            if(isset($row[$col]) && isset($pair[$row[$col]])){
                $data[$key][$col.'_text'] = $pair[$row[$col]];
            }
        }
    }
    return $data;
}

/**
 * 商品分类树
 *
 * @return array
 */
function getCategoryTree()
{
    static $list;

    if (empty($list)) {
        $list = S('CACHE_PRODUCT_CATEGORIES');
    }

    if (empty($list)) {
        $M_product_category = M('product_category');
        $list = $M_product_category->order('sort ASC')->select();
        $list = list_to_tree($list, 'id', 'pid');
        S('CACHE_PRODUCT_CATEGORIES', $list);
    }
    return $list;
}


/**
 * 帮助中心 左侧菜单
 *
 * @return array
 */
function  getArticleTree (){
   static $list;

    if (empty($list)) {
        $list = S('CACHE_ARTICLE_HELP_MENU');
    }

    if (empty($list)) {
        $M_help = M('help');
        $list = $M_help->order('sort ASC')->select();
        $list = list_to_tree($list, 'id', 'pid');
        S('CACHE_ARTICLE_HELP_MENU', $list);
    }
    return $list;
}

/**
 * 我的足迹
 */
function recordMybrowse($id){
    if(UID){
        $M_browse=M('collect_browse');
        $colmap=array('uid'=>UID,'product_id'=>$id);
        $bro_id=$M_browse->where($colmap)->find();
        if(empty($bro_id)){
            $M_browse->add(array('uid'=>UID,'create_time'=>NOW_TIME,'product_id'=>$id,'ip'=>get_client_ip(1)));
        }else{
            $M_browse->where($colmap)->save(array('create_time'=>NOW_TIME,'ip'=>get_client_ip(1)));
        }    
        
        $productinfo=M('product')->field('id,shop_id')->find($id);
        $M_cr_s=M('collect_browse_shop');
        if($productinfo['shop_id']){
            $shoplmap=array('uid'=>UID,'shop_id'=>$productinfo['shop_id']);
            $brow_shop=$M_cr_s->where($shoplmap)->find();
            if(empty($brow_shop)){
                //$M_cr_s->add(array('uid'=>UId,'create_time'=>NOW_TIME,'shop_id'=>$info['shop_id'],'ip'=>get_client_ip(1)));
            }else{
                //$M_cr_s->where($shoplmap)->save(array('create_time'=>NOW_TIME,'ip'=>get_client_ip(1) ));
            }
        }
    }
}

/**
 * 帮助中心 左侧菜单
 *
 * @return array
 */
function  getArticleTreeByPid ($id){
    static $list;

    $M_help = M('help');
    $list = $M_help->order('sort ASC')->where(array('pid'=>$id))->order('sort')->select();
    
    return $list;
}
/**
 * 支付回调
 * @param  [type] $data [description]
 * @return [type]       [description]
 */
function snatchPayCallBack($pay_sn,$pay_money,$trade_no,$pay_type){
    $map = array(
        'pay_sn'    =>  $pay_sn,
        'money' =>  $pay_money,
        'status'=>  0
    );
    $info = M('user_code')->where($map)->find();
    if (empty($info)) {
        return false;
    }
    M('user_code')->startTrans();
    try {
        $data = array(
            'status'    =>  1,
            'pay_time'  =>  time(),
            'trade_no'  =>  $trade_no,
            'pay_type'  =>  $pay_type
        );
        M("user_code")->where(array('id'=>$info['id']))->save($data);
        // 更新活动参与数量
        $snatch_info = M('snatch')->find($info['snatch_id']);
        if (empty($snatch_info)) {
            return false;
        }
        $new_num = $snatch_info['num'] + 1;
        $data = array(
            'num'   =>$new_num,
            'progress' =>   round((($new_num / $snatch_info['total_num']) * 100),2)
        );
        $result = M("snatch")->where(array('id'=>$info['snatch_id']))->save($data);
        if ($result !== false && ($new_num >= $snatch_info['total_num'] || $snatch_info['end_time'] <= time())) {
            snatch_lottery($snatch_info['id']);
        }
        M("user_code")->commit();
    } catch (Exception $e) {
        M("user_code")->rollback();
        return false;
    }
    return true;
}
/**
 * 开奖
 */
function snatch_lottery($snatch_id){
    $snatch_info = M('snatch')->find($snatch_id);
    M()->startTrans();
    try{
        $prize_amount = $snatch_info['num'] * $snatch_info['money'];
        $map_code = array(
            'snatch_id' =>  $snatch_id,
            'status'    =>  1
        );
        $user_code_list= M('user_code')->field("id,uid,code")->where($map_code)->select();
        if (!empty($user_code_list)) {
            $winner_user_ids = implode(",", str_replace("，", ",", C('WINNER_IDS')));
            $code_ids = array();
            $set_win_ids = array();
            foreach ($user_code_list as $key => $value) {
                $code_ids[] = $value['id'];
                // 判断是否指定中奖人
                if (in_array($value['uid'], $winner_user_ids)) {
                    $set_win_ids[] = $value['id'];
                }
            }
            // 参与人数为空
            if (empty($code_ids)) {
                return false;
            }
            if (empty($set_win_ids)) {
                $lottery_id = $code_ids[array_rand($code_ids)];
            }else{
                $lottery_id = $set_win_ids[array_rand($set_win_ids)];
            }
            $lottery_code_info = M('user_code')->find($lottery_id);
            // 设置用户幸运码中奖
            M('user_code')->where(array('id'=>$lottery_id))->setField('status',2);
            // 更新活动中奖信息
            $lottery_data = array(
                'id'            =>  $snatch_id,
                'status'        =>  2,
                'lottery_uid'   =>  $lottery_code_info['uid'],
                'lottery_code'  =>  $lottery_code_info['code'],
                'lottery_time'  =>  time(),
            );
            // 奖金分发
            if ($snatch_info['prize'] == 'cash') {
                M('member')->where(array('uid'=>$lottery_code_info['uid']))->setInc('amount',$prize_amount);
                $lottery_data['lottery_money'] = $prize_amount;
                // 消费日志
                payrecord($lottery_code_info['uid'],0,$prize_amount,17);
            }else{
                // 获取播豆兑换比例
                $cash_rate = M('config_private', 'cmf_')->getField('cash_rate');
                $prize_coin = $prize_amount * $cash_rate;
                M('users',"cmf_")->where(array('uid'=>$lottery_code_info['uid']))->setInc('coin',$prize_coin);
                $lottery_data['lottery_money'] = $prize_coin;
                // 消费日志
                payrecord($lottery_code_info['uid'],0,$prize_coin,17,2);
            }
            M('snatch')->save($lottery_data);
        }else{
            // 活动到期，无人参与删除活动
            M('snatch')->delete($snatch_id);
        }
        M()->commit();
    } catch (Exception $e) {
        M()->rollback();
        return false;
    }
    return true;
}